#include "param.h"
#include "types.h"
#include "stat.h"
#include "user.h"
#include "fs.h"
#include "fcntl.h"
#include "syscall.h"
#include "traps.h"
#include "memlayout.h"

// 用户所能获得的消息结构体
struct msg
{
    int type;
    char *dataaddr;
} s1, s2, g;

void msg_test()
{
    int mqid = mqget(123); // 使用消息队列
    int pid = fork();
    if (pid == 0)
    {
        s1.type = 1;
        s1.dataaddr = "This is the first message!";
        msgsnd(mqid, &s1, 27); // 开始发送消息1
        s1.type = 2;
        s1.dataaddr = "Hello, another message comes!";
        msgsnd(mqid, &s1, 30); // 开始发送消息2
        s1.type = 3;
        s1.dataaddr = "This is the third message, and this is message has great characters!";
        msgsnd(mqid, &s1, 70);
        printf(1, "all message have been sent.\n");
    }
    else if (pid > 0)
    {
        sleep(10); // 保证子进程写入消息后再去读取
        g.dataaddr = malloc(70);
        g.type = 2;
        msgrcv(mqid, &g, 30); // 读入消息2
        printf(1, "receive the %dth message: %s\n", 2, g.dataaddr);
        g.type = 1;
        msgrcv(mqid, &g, 27); // 读入消息1
        printf(1, "receive the %dth message: %s\n", 1, g.dataaddr);
        g.type = 3;
        msgrcv(mqid, &g, 70); // 读入消息3
        printf(1, "receive the %dth message: %s\n", 3, g.dataaddr);
        wait();
    }
    exit();
}

int main(int argc, char const *argv[])
{
    msg_test();
    return 0;
}
